import { FC, ReactElement, useEffect, useState } from 'react'
import { Table, Card, Button, Modal, message, Tag, Space } from 'antd'
import { Dispatch, RoleModelState, connect, RoleListType } from 'umi'
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import AddRole from './components/add-role'
import EditRole from './components/edit-role'
import RoleMenu from './components/role-menu'
import styles from './index.less'
interface IProps {
  dispatch: Dispatch
  roleModel: RoleModelState
}
const Role: FC<IProps> = ({ dispatch, roleModel }): ReactElement => {
  const [addShow, setAddShow] = useState<boolean>(false)
  const [editShow, setEditShow] = useState<boolean>(false)
  const [roleMenuShow, setRoleMenuShow] = useState<boolean>(false)
  const [record, setRecord] = useState<RoleListType | undefined>(undefined)
  const [pageNum, setPageNum] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)
  const { roleList } = roleModel

  const paginationProps = {
    current: pageNum, //当前页码
    pageSize, // 每页数据条数
    showTotal: () => <span>总共{total}项</span>,
    total, // 总条数
    onChange: (page: number, pageSize: number) =>
      handlePageChange(page, pageSize), //改变页码的函数
    hideOnSinglePage: false,
    showSizeChanger: false
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNum(page)
    setPageSize(pageSize)
  }

  // 新增角色信息
  const addRole = () => {
    setAddShow(true)
  }
  // 编辑角色信息
  const editRole = (record: RoleListType) => {
    setRecord(record)
    setEditShow(true)
  }
  // 删除角色信息
  const deleteRole = (roleCode: string) => {
    Modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除该角色吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'roleModel/function_deleteRoleInfo',
          payload: {
            roleCode
          },
          callback: (response) => {
            if (response.code === 200) {
              message.success('删除成功')
              getRoleList()
            }
          }
        })
      }
    })
  }
  //   查询系统角色列表
  const getRoleList = () => {
    dispatch({
      type: 'roleModel/function_getRoleList'
    })
  }

  // 关联角色菜单
  const roleMenu = (record: RoleListType) => {
    setRecord(record)
    setRoleMenuShow(true)
  }

  const formatStatus = (status: string) => {
    const STATUS = {
      0: <Tag color="red">禁用</Tag>,
      1: <Tag color="green">启用</Tag>
    }
    return STATUS[status]
  }
  const columns: ColumnsType<RoleListType> = [
    {
      title: '序号',
      key: 'index',
      align: 'center',
      render: (text: string, record: RoleListType, index: number) => {
        return (
          <span>
            {((pageNum - 1) * pageSize + (index + 1))
              .toString()
              .padStart(2, '0')}
          </span>
        )
      }
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'desc',
      key: 'desc',
      align: 'center',
      render: (text: string) => {
        return <span>{text ? text : '暂无'}</span>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text: string) => formatStatus(text)
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      render: (text: string, record: RoleListType) => {
        return (
          <Space size="large">
            <Button type="primary" onClick={() => editRole(record)}>
              修改
            </Button>
            <Button type="primary" onClick={() => roleMenu(record)}>
              关联菜单
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => deleteRole(record.code)}
            >
              删除
            </Button>
          </Space>
        )
      }
    }
  ]

  const handleUpdate = () => {
    getRoleList()
  }

  useEffect(() => {
    getRoleList()
  }, [])

  useEffect(() => {
    setTotal(roleList.length)
    if (Math.ceil(roleList.length / 10) < pageNum && pageNum > 1) {
      setPageNum((prev) => prev - 1)
    }
  }, [roleList])
  return (
    <>
      <div className={styles.container}>
        <Card>
          <Button
            icon={<PlusOutlined />}
            onClick={addRole}
            style={{ marginBottom: '20px' }}
          >
            添加角色
          </Button>
          <Table
            dataSource={roleList}
            columns={columns}
            rowKey="code"
            pagination={paginationProps}
          />
        </Card>

        {/* 添加角色 */}
        <AddRole
          visible={addShow}
          hide={() => {
            setAddShow(false)
          }}
          update={handleUpdate}
        />

        {/* 编辑角色 */}
        <EditRole
          visible={editShow}
          hide={() => {
            setEditShow(false)
          }}
          record={record}
          update={handleUpdate}
        />

        {/* 角色关联菜单 */}
        <RoleMenu
          visible={roleMenuShow}
          hide={() => {
            setRoleMenuShow(false)
          }}
          record={record}
        />
      </div>
    </>
  )
}

const mapStateToProps = ({ roleModel }: { roleModel: RoleModelState }) => {
  return {
    roleModel
  }
}

export default connect(mapStateToProps)(Role)
